<?php
class pk_user extends BaseModel implements Retrievable {

	var $level;
	var $subnet;
	var $email;
	var $new_email;
	var $username;
	var $password;
	var $salt;
	var $enabled;
	var $verified;
	var $last_login;
	var $last_active;
	var $status;
	var $logins;
	var $timezone;
	var $profile_views;
	var $updated;
	var $blocklist;
	var $photo;
	var $privacy_search;
	var $privacy_profile;
	var $privacy_comments;
	var $referer;
	var $points_allowed;
	var $emailed;
	var $sports;
	
    public function pk_user($values) {
        parent::__construct($values);
    }

    public function validate() {
        $errors = Array();
		return (count($errors) === 0 ? true : $errors);
    }

    public static function get($id, $primaryKey='id') {
        return parent::get($id, __CLASS__, $primaryKey);
    }
    
    public static function getAll($searchArray=Array(), $sortArray=Array(), $limit=0) {
        return parent::getAll($searchArray, $sortArray, __CLASS__, $limit);
    }
    
    public function register() {    	
        $this->enabled = '1';
        $this->verified = '1';
    }
    
    public function login($remember=false) {
    	$_SESSION['pk_user'] = $this->id;
    	if($remember) {
    		$cookieValue = sprintf('%u', crc32($this->id));
	    	setcookie("pk_user", $cookieValue, time() + (2*24*60*60), "/", str_replace('www', '', $_SERVER['SERVER_NAME']));
    	}
    	#TODO: update time
    }
    
    public static function isLoggedIn() {
    	return isset($_SESSION['pk_user']);
    }
    
    public static function id() {
    	return isset($_SESSION['pk_user']) ? $_SESSION['pk_user'] : '0';
    }
    
    public function logout() {
    	if(isset($_COOKIE['pk_user'])) {
    		setcookie("pk_user", "0", time()-1, "/", str_replace('www', '', $_SERVER['HTTP_HOST']));
    	}
    	unset($_SESSION['pk_user']);
    	#TODO: update time
    }
    
    public function exists() {
    	return ($this->id > 0);
    }
    
    public static function getRandom9() {    
    	$cache = DOC_ROOT . "/webroot/cache/map_". md5(date("mdY")) . ".txt";
    	if(file_exists($cache)) {
    		$users = unserialize(file_get_contents($cache));
    	} else {
    		$users = pk_user::getAll(array("photo"=>"[:custom] != 'default.jpg'"), array("RAND()"), 9);
    		$fh = fopen($cache, "w");
    		if($fh) {
    			fwrite($fh, serialize($users));
    			fclose($fh);
    		}
    	}
    	return $users;
    }
    
}
?>